<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.mobile" placeholder="手机号" class="filter-item search-input" clearable />
      <el-input v-model="listQuery.nickName" placeholder="昵称" class="filter-item search-input" clearable />
      <el-date-picker
        v-model="listQuery.startTime"
        placeholder="注册时间（开始）"
        value-format="yyyy-MM-dd HH:mm:ss"
        type="datetime"
        class="filter-item search-input"
      />
      <el-date-picker
        v-model="listQuery.endTime"
        placeholder="注册时间（结束）"
        type="datetime"
        value-format="yyyy-MM-dd HH:mm:ss"
        class="filter-item search-input"
      />
      <el-select
        v-model="listQuery.peerId"
        placeholder="分公司"
        clearable
        style="width: 190px"
        class="filter-item search-input"
      >
        <el-option v-for="item in peerOptions" :key="item.peerId" :label="item.name" :value="item.peerId" />
      </el-select>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-download" @click="handleExport">
        导出
      </el-button>
      <!--      <el-button class="filter-item" type="primary" icon="el-icon-plus" @click="handleFilter">-->
      <!--        添加-->
      <!--      </el-button>-->
    </div>

    <!--  列表  -->
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="ID">
        <template slot-scope="{row}">
          <span>{{ row.ID }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号" align="center">
        <template slot-scope="{row}">
          <span>{{ row.mobile }}</span>
        </template>
      </el-table-column>
      <el-table-column label="昵称" align="center">
        <template slot-scope="{row}">
          <span>{{ row.nickName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="性别" align="center">
        <template slot-scope="{row}">
          <span style="font-weight :bold;">{{ row.sex }}</span>
        </template>
      </el-table-column>
      <el-table-column label="积分" align="center">
        <template slot-scope="{row}">
          <router-link class="link-type" :to="'/member/integralLogList/' + row.ID">{{ row.integral }}</router-link>
        </template>
      </el-table-column>
      <el-table-column label="所属业务员" min-width="100px" align="center">
        <template slot-scope="{row}">
          <span class="link-type" @click="getRelation(row)" v-html="row.sales" />
        </template>
      </el-table-column>
      <el-table-column label="所属公司" align="center">
        <template slot-scope="{row}">
          <span v-html="row.peer" />
        </template>
      </el-table-column>
      <el-table-column label="注册时间" min-width="100px" align="center">
        <template slot-scope="{row}">
          <span v-html="row.registTime" />
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="100px" align="center">
        <template slot-scope="{row}">
          <el-button size="small" type="primary" icon="el-icon-edit" @click="handleUpdate(row)">编辑</el-button>
          <el-button size="small" type="danger" plain @click="()=>{dialogRechargeVisible = true; userId=row.ID}">充值</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="层级关系" :visible.sync="dialogRelationVisible">
      <el-tree :data="relation" :props="{children:'child', label:'nickName'}" />
    </el-dialog>

    <el-dialog title="充值" :visible.sync="dialogRechargeVisible">
      <el-form id="recharge">
        <el-form-item label="充值金额" prop="mobile">
          <el-input v-model="rechargePrice" placeholder="请输入充值金额（正整数）" type="number" oninput="value=value.replace(/[^0-9]/g,'')" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogRechargeVisible = false">
          取消
        </el-button>
        <el-button type="primary" :disabled="rechargeSubmitDisabled" @click="recharge">
          提交
        </el-button>
      </div>
    </el-dialog>

    <!-- 编辑页 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" fullscreen>
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="saveData"
        label-position="left"
        label-width="auto"
        style="width: 100%; margin-left:10px;"
      >
        <el-form-item label="用户ID" prop="mobile">
          <el-input v-model="saveData.ID" placeholder="请输入用户ID" disabled />
        </el-form-item>
        <el-form-item label="电话号" prop="mobile">
          <el-input v-model="saveData.mobile" placeholder="请输入电话号" />
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickName">
          <el-input v-model="saveData.nickName" placeholder="请输入用户昵称" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="trueName">
          <el-input v-model="saveData.trueName" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="用户unionId" prop="trueName">
          <el-input v-model="saveData.unionId" placeholder="请输入用户unionId" />
        </el-form-item>
        <el-form-item label="用户openId" prop="openId">
          <el-input v-model="saveData.openId" placeholder="请输入用户openId" />
        </el-form-item>
        <!--        <el-form-item label="用户头像" prop="openId">-->
        <!--          <el-input v-model="saveData.openId" placeholder="请输入用户openId" />-->
        <!--        </el-form-item>-->
        <el-form-item label="性别" prop="sex">
          <el-select v-model="saveData.sex" class="filter-item" placeholder="请选择性别">
            <el-option
              v-for="item in [
                {label:'男', value:'1'},
                {label:'女', value:'2'},
              ]"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="积分余额" prop="integral">
          <el-input v-model="saveData.integral" placeholder="请输入积分余额" />
        </el-form-item>
        <el-form-item label="积分是否冻结" prop="frozen">
          <el-input v-model="saveData.frozen" placeholder="请输入积分是否冻结" />
        </el-form-item>
        <el-form-item label="所属业务员ID" prop="salesId">
          <el-input v-model="saveData.salesId" placeholder="请输入所属业务员ID" />
        </el-form-item>
        <el-form-item label="所属分公司ID" prop="peerId">
          <el-input v-model="saveData.peerId" placeholder="请输入所属分公司ID" />
        </el-form-item>
        <el-form-item label="上级用户ID" prop="fromId">
          <el-input v-model="saveData.fromId" placeholder="请输入上级用户ID" />
        </el-form-item>
        <el-form-item label="注册时间" prop="registTime">
          <el-input v-model="saveData.registTime" placeholder="请输入注册时间" disabled />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" :disabled="submitDisabled" @click="dialogStatus==='create'?createData():updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.perPage"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { listStartCity, listSelection } from '@/api/selectOptions'
import { toSelectOptions } from '@/utils/common'
import Pagination from '@/components/Pagination'
import { list, get, update, relation, recharge } from '@/api/member'

export default {
  components: {
    Pagination
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        perPage: 20,
        csv: undefined, // 为1时，导出
        mobile: undefined,
        nickName: undefined,
        startTime: undefined,
        endTime: undefined,
        peerId: undefined
      },
      peerOptions: undefined,
      dialogRelationVisible: false,
      dialogRechargeVisible: false,
      userId: undefined,
      rechargePrice: 1,
      relation: [],

      // 以下为编辑页属性
      rechargeSubmitDisabled: false,
      submitDisabled: false,
      dialogStatus: '',
      dialogFormVisible: false,
      saveData: {
        ID: undefined,
        mobile: undefined,
        nickName: undefined,
        trueName: undefined,
        unionId: undefined,
        openId: undefined,
        pic: undefined,
        sex: undefined,
        integral: undefined,
        frozen: undefined,
        salesId: undefined,
        peerId: undefined,
        fromId: undefined,
        registTime: undefined
      },
      resetSaveData() {
        this.saveData = {
          ID: undefined,
          mobile: undefined,
          nickName: undefined,
          trueName: undefined,
          unionId: undefined,
          openId: undefined,
          pic: undefined,
          sex: undefined,
          integral: undefined,
          frozen: undefined,
          salesId: undefined,
          peerId: undefined,
          fromId: undefined,
          registTime: undefined
        }
      },
      textMap: {
        update: '编辑',
        create: '添加'
      },
      rules: {
        ID: [{ required: true, message: '用户ID不能为空', trigger: 'change' }],
        mobile: [{ required: true, message: '电话号不能为空', trigger: 'change' }],
        nickName: [{ required: true, message: '用户昵称不能为空', trigger: 'change' }],
        trueName: [{ required: true, message: '真实姓名不能为空', trigger: 'change' }],
        unionId: [{ required: true, message: '用户unionId不能为空', trigger: 'change' }],
        openId: [{ required: true, message: '用户openId不能为空', trigger: 'change' }],
        // pic: [{required: true, message: '用户头像不能为空', trigger: 'change'}],
        sex: [{ required: true, message: '性别不能为空', trigger: 'change' }],
        integral: [{ required: true, message: '积分余额不能为空', trigger: 'change' }],
        frozen: [{ required: true, message: '积分是否冻结不能为空', trigger: 'change' }],
        salesId: [{ required: true, message: '所属业务员ID不能为空', trigger: 'change' }],
        peerId: [{ required: true, message: '所属分公司ID不能为空', trigger: 'change' }],
        fromId: [{ required: true, message: '上级用户ID不能为空', trigger: 'change' }],
        registTime: [{ required: true, message: '注册时间不能为空', trigger: 'change' }]
      }
    }
  },
  created() {
    this.getStartCityOptions()
    this.getPeerOptions()
    this.getList()
  },
  methods: {
    recharge(price) {
      this.rechargeSubmitDisabled = true
      recharge({ ID: this.userId, price: this.rechargePrice }).then(response => {
        this.rechargeSubmitDisabled = false
      })
    },
    getRelation(row) {
      this.dialogRelationVisible = true
      relation({ ID: row.ID }).then(response => {
        // this.relation.push()
      })
    },
    getList() {
      this.listLoading = true
      list(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.total
        this.listLoading = false
      })
    },
    getStartCityOptions() {
      listStartCity().then(response => {
        this.startCityOptions = toSelectOptions(response.data)
      })
    },
    getPeerOptions() {
      listSelection().then(response => {
        this.peerOptions = response.data
      })
    },
    // handleCreate() {
    //   this.resetSaveData()
    //   this.dialogFormVisible = true
    //   this.$nextTick(() => {
    //     this.$refs['dataForm'].clearValidate()
    //   })
    // },
    // createData() {
    //   this.submitDisabled = true
    //   this.$refs['dataForm'].validate((valid) => {
    //     if (valid) {
    //       create(this.saveData).then(() => {
    //         this.list.unshift(this.saveData)
    //         this.dialogFormVisible = false
    //         this.$notify({
    //           title: '成功',
    //           message: '创建成功',
    //           type: 'success',
    //           duration: 2000
    //         })
    //         this.submitDisabled = false
    //         this.getList()
    //       })
    //     } else {
    //       this.submitDisabled = false
    //     }
    //   })
    // },
    handleUpdate(row) {
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      get({ ID: row.ID }).then(response => {
        this.saveData = Object.assign({}, response.data[0]) // copy obj
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      })
    },
    updateData() {
      this.submitDisabled = true
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          update(this.saveData).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
            this.submitDisabled = false
            this.getList()
          })
        } else {
          this.submitDisabled = false
        }
      })
    },
    handleDelete(row, index) {
      this.$notify({
        title: '成功',
        message: '删除成功',
        type: 'success',
        duration: 2000
      })
      this.list.splice(index, 1)
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleExport() {
      list(Object.assign(this.listQuery, { csv: 1 }), 'arraybuffer').then(response => {
        const content = response
        // 组装a标签
        const elink = document.createElement('a')
        // 设置下载文件名
        elink.download = '附件.csv'
        elink.style.display = 'none'
        const blob = new Blob([content], { type: '.csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel' })
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        document.body.removeChild(elink)
        this.listQuery.csv = 0
      })
    },
    toIntegralLogList(uid) {

    }
  }
}
</script>

<style>
.search-input {
  width: 150px;
  margin-right: 15px;
}
#recharge .el-input--medium {
  width: 90%;
}
</style>
